package com.dlc.shop.user.common.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.app.dto.ProductDto;
import com.dlc.shop.bean.app.dto.ShopCartItemDto;
import com.dlc.shop.bean.event.LoadProdMemberPriceEvent;
import com.dlc.shop.bean.event.LoadProdOffersEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.bean.vo.search.EsProductSearchVO;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.util.Arith;
import com.dlc.shop.service.UserExtensionService;
import com.dlc.shop.user.common.dao.UserLevelMapper;
import com.dlc.shop.user.common.model.UserLevel;
import jodd.util.StringUtil;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 加载商品会员价信息
 * @author yami
 */
@Component("loadProdMemberPriceListener")
@AllArgsConstructor
public class LoadProdMemberPriceListener {

    private final UserLevelMapper userLevelMapper;
    private final UserExtensionService userExtensionService;

    @EventListener(LoadProdOffersEvent.class)
    public void loadProdListLevelListener(LoadProdOffersEvent event) {
        // 购物车会员价计算（根据当前用户是否存在会员进行计算（品牌&平台））
        if(CollectionUtil.isNotEmpty(event.getShopCartItems())){
            this.calMemberPrice(event);
        }
        // 装修用的会员价计算
        if(CollectionUtil.isEmpty(event.getProductSearchList())){
            return;
        }
        // 平台会员权益
        Integer userLevelType = 1;
        String userId = event.getUserId();
        if (Objects.nonNull(userId)) {
            UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>()
                    .eq(UserExtension::getUserId, userId));
            userLevelType = userExtension.getLevelType();
        }
        List<UserLevel> userLevels = userLevelMapper.listLevelAndCategoryByShopId(Constant.PLATFORM_SHOP_ID, userLevelType);
        // 店铺会员权益
        if (Objects.nonNull(userId)) {
            Set<Long> shopIds = event.getProductSearchList().stream().map(ProductSearchVO::getShopId).collect(Collectors.toSet());
            List<UserLevel> brandLevelList = userLevelMapper.listLevelAndCategoryByUserId(userId, shopIds);
            userLevels.addAll(brandLevelList);
        }
        for (ProductSearchVO productSearchVO : event.getProductSearchList()) {
            double minPlatformDiscount = getMinPlatformDiscount(userLevels, productSearchVO.getCategoryId(), productSearchVO.getBrandId());
            productSearchVO.setMemberPrice(Arith.div(Arith.mul(productSearchVO.getPrice(), minPlatformDiscount), 10, 2));
        }

    }

    @EventListener(LoadProdMemberPriceEvent.class)
    public void loadProdMemberPrice(LoadProdMemberPriceEvent event) {
        if (CollUtil.isEmpty(event.getProductDtos())) {
            return;
        }
        List<UserLevel> userLevels = userLevelMapper.listLevelAndCategoryByShopId(Constant.PLATFORM_SHOP_ID, 1);
        for (ProductDto productDto : event.getProductDtos()) {
            double minPlatformDiscount = getMinPlatformDiscount(userLevels, productDto.getCategoryId(), null);
            productDto.setMemberPrice(Arith.div(Arith.mul(productDto.getPrice(), minPlatformDiscount), 10, 2));
        }
    }

    private double getMinPlatformDiscount(List<UserLevel> userLevels, Long categoryId, Long shopId) {
        double minPlatformDiscount = 10.0;
        for (UserLevel userLevel : userLevels) {
            if (Objects.equals(userLevel.getDiscountType(), 1) && !userLevel.getCategoryIds().contains(categoryId)) {
                continue;
            }
            if (Objects.nonNull(userLevel.getShopId())
                    && !Objects.equals(userLevel.getShopId(), Constant.PLATFORM_SHOP_ID)
                    && !Objects.equals(userLevel.getShopId(), shopId)) {
                continue;
            }
            // 获取最小的折扣也就是最大的优惠进行计算
            if (userLevel.getDiscount() < minPlatformDiscount) {
                minPlatformDiscount = userLevel.getDiscount();
            }
        }
        return minPlatformDiscount;
    }

    /**
     * 计算商品会员价格（只计算店铺会员，不计算平台会员）
     * @param event
     */
    private void calMemberPrice(LoadProdOffersEvent event) {
        String userId = event.getUserId();
        List<ShopCartItemDto> shopCartItems = event.getShopCartItems();
        if (CollectionUtils.isEmpty(shopCartItems)) {
            return;
        }
        // 购物车商品按店铺进行分类，并查出用户对应店铺的会员信息
        Map<Long, List<ShopCartItemDto>> shopCartsMap = shopCartItems.stream().collect(Collectors.groupingBy(ShopCartItemDto::getShopId));
        List<UserLevel> shopLevelList = userLevelMapper.listLevelAndCategoryByUserId(userId, shopCartsMap.keySet());
        Map<Long, UserLevel> shopLevelMap = shopLevelList.stream().collect(Collectors.toMap(UserLevel::getShopId, userLevel -> userLevel));
        // 遍历店铺，获取会员，计算价格
        double discountRate;
        for (Map.Entry<Long, List<ShopCartItemDto>> entry : shopCartsMap.entrySet()) {
            UserLevel shopLevel = null;
            if(shopLevelMap.containsKey(entry.getKey())){
                shopLevel = shopLevelMap.get(entry.getKey());
            }
            for (ShopCartItemDto shopCartItem : entry.getValue()) {
                shopCartItem.setMemberAmount(shopCartItem.getPrice());
                shopCartItem.setMemberTotalAmount(shopCartItem.getActualTotal());
                // 店铺运费减免
                if (shopLevel != null
                        && shopLevel.getIsFreeFee() == 1) {
                    shopCartItem.setFreeFreightAmount(shopCartItem.getDeliveryAmount());
                    shopCartItem.setDeliveryAmount(0.0);
                }
                // 店铺商品打折
                boolean isDiscount = shopLevel != null
                        && shopLevel.getDiscount() < 10.0
                        && (shopLevel.getDiscountType() == 0 || shopLevel.getCategoryIds().contains(shopCartItem.getCategoryId()));
                if (isDiscount) {
                    double memberAmount = Arith.div(Arith.mul(shopCartItem.getMemberAmount(), shopLevel.getDiscount()), 10, 2);
                    memberAmount = Arith.div(Arith.mul(memberAmount, 100), 100, 2);
                    shopCartItem.setMemberAmount(Math.max(memberAmount, 0.01));
                    double memberTotalAmount = Arith.div(Arith.mul(shopCartItem.getMemberTotalAmount(), shopLevel.getDiscount()), 10, 2);
                    memberTotalAmount = Arith.div(Arith.mul(memberTotalAmount, 100), 100, 2);
                    shopCartItem.setMemberTotalAmount(Math.max(memberTotalAmount, 0.01));
                    shopCartItem.setLevel(shopLevel.getLevel());
                }
            }
        }
    }

    @EventListener(LoadProdMemberPriceEvent.class)
    public void loadEsProdMemberPrice(LoadProdMemberPriceEvent event) {
        if (Objects.isNull(event.getEsProductSearchVOList())){
            return;
        }
        UserExtension extension = null;
        //用户登录状态时，计算店铺会员价
        if(Objects.nonNull(event.getUserId())){
            calMemberPrice(event);
            extension = userExtensionService.getOne(
                    new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, event.getUserId()));
            if (Objects.nonNull(extension) && extension.getLevel() == null) {
                extension.setLevel(Constant.USER_LEVEL_INIT);
            }
        }
    }

    private void calMemberPrice(LoadProdMemberPriceEvent event) {

        List<ProductSearchVO> products = event.getEsProductSearchVOList().get(0).getProducts();
        Set<Long> shopIdSet = products.stream().map(ProductSearchVO::getShopId).collect(Collectors.toSet());
        if(CollectionUtil.isEmpty(products) || StringUtil.isBlank(event.getUserId())){
            return;
        }
        //获取用户的店铺会员信息
        List<UserLevel> userLevelList = userLevelMapper.listLevelAndCategoryByUserId(event.getUserId(), shopIdSet);
        if(CollectionUtil.isEmpty(userLevelList)){
            return;
        }
        Map<Long, UserLevel> shopLevelMap = userLevelList.stream().collect(Collectors.toMap(UserLevel::getShopId, userLevel -> userLevel));
        for (ProductSearchVO productSearchVO : products) {
            if (Objects.isNull(productSearchVO.getShopId()) || !shopLevelMap.containsKey(productSearchVO.getShopId())) {
                continue;
            }
            UserLevel shopLevel = null;
            shopLevel = shopLevelMap.get(productSearchVO.getShopId());
            // 店铺商品打折
            boolean isDiscount = shopLevel != null
                    && shopLevel.getDiscount() < 10.0
                    && (shopLevel.getDiscountType() == 0 || shopLevel.getCategoryIds().contains(productSearchVO.getCategoryId()));
            double discountRate = shopLevel.getDiscount();
            // 放入会员价信息
            if(isDiscount){
                productSearchVO.setMemberPrice(Arith.div(Arith.mul(productSearchVO.getPrice(), discountRate), 10, 2));
                // sku价格最低只能为0.01
                if (productSearchVO.getMemberPrice() < Constant.MIN_PRODUCT_AMOUNT) {
                    productSearchVO.setMemberPrice(Constant.MIN_PRODUCT_AMOUNT);
                }
            }

        }

    }

    private void calMemberPlatformPrice(Map<Long, List<UserLevel>> userLevelMap,EsProductSearchVO esProductSearchVO,
                                        List<UserLevel> platformUserLevels,Boolean isPlatformMember,UserLevel level ) {
        List<UserLevel> userLevelsList = new ArrayList<>();
        List<UserLevel> userLevels = userLevelMap.get(esProductSearchVO.getShopInfo().getShopId());
        if (CollUtil.isNotEmpty(userLevels)){
            userLevelsList.addAll(userLevels);
        }

        double minDiscount = 10.0;
        Integer brandLevel = 10;
        double minPlatformDiscount = 10.0;
        Integer platformLevel = 10;

        List<ProductSearchVO> products = esProductSearchVO.getProducts();
        for (ProductSearchVO product : products) {
            for (UserLevel userLevel : userLevelsList) {
                if(Objects.equals(userLevel.getDiscountType(),1) && !userLevel.getCategoryIds().contains(product.getCategoryId())){
                    continue;
                }
                if(userLevel.getDiscount() < minDiscount){
                    minDiscount = userLevel.getDiscount();
                    brandLevel = userLevel.getLevel();
                }
            }

            for (UserLevel userLevel : platformUserLevels) {
                if(isPlatformMember){
                    platformLevel = level.getLevel();
                    minPlatformDiscount = level.getDiscount();
                    break;
                }
                if(Objects.equals(userLevel.getDiscountType(),1) && !userLevel.getCategoryIds().contains(product.getCategoryId())){
                    continue;
                }
                if(userLevel.getDiscount() < minPlatformDiscount){
                    minPlatformDiscount = userLevel.getDiscount();
                    platformLevel = userLevel.getLevel();
                }
            }

            // 放入会员价信息
            if(brandLevel != 10){
                product.setMostMemberAmount(Arith.div(Arith.mul(product.getPrice(), minDiscount), 10, 2));
            }
            if(platformLevel != 10) {
                product.setMostPlatformMemberAmount(Arith.div(Arith.mul(product.getPrice(), minPlatformDiscount), 10, 2));
            }

        }

        }
}
